<template>
  <base-breadcrumb :title="$route.meta.title" :breadcrumb="!isAudit">
    <!-- 督办事项承办事项 的 事项管理详情页面 -->
    <a-form-model
      ref="ruleForm"
      :model="form"
      :label-col="{ span: 6 }"
      :wrapper-col="{ span: 18 }"
      :rules="editModel != 0 ? rules : {}"
    >
      <a-spin :spinning="loading">
        <!-- 表格 -->
        <a-card :bordered="false">
          <title-name title="项目基本信息" />
          <custom-form
            :form-list="formList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
          />
        </a-card>
        <!--反馈结果  该页面为查看页面&&结果不等于待提交 && 反馈结果有数据-->
        <a-card
          v-if="editModel == 0 && form.overseeStatus != 'DRAFT' && form.overseeStatus != 'NO_FEEDBACK'"
          :bordered="false"
        >
          <title-name title="反馈结果" />
          <custom-form
            :form-list="resultList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
          >
            <!-- 附件上传 -->
            <template #feedbackList>
              <file-link :file-list="form.feedbackVO ? form.feedbackVO.feedbackFile : []" />
            </template>
          </custom-form>
        </a-card>
        <!--延期申请-->
        <a-card
          v-if="editModel == 0 && form.delayApplyVO"
          :bordered="false"
        >
          <title-name title="延期申请" />
          <custom-form
            :form-list="delayApplyList"
            :form="form"
            :edit-model="editModel == 0 ? 'V' : ''"
            @getOption="(name, e) => (name === 'formId' ? (formCode = e.code) : null)"
          >
            <!-- 附件上传 -->
            <template #delayApplyfileList>
              <file-link :file-list="form.delayApplyVO ? form.delayApplyVO.delayApplyFile : []" />
            </template>
          </custom-form>
        </a-card>
      </a-spin>
      <!-- 页脚操作栏 -->
      <div v-if="!isConsultation" class="btn_box page-btn-right-top">
        <a-button
          v-if="editModel != 0"
          :loading="loading[0]"
          type="primary"
          class="button_right"
          @click="handleSubmit(1)"
        >
          保存草稿
        </a-button>
        <a-button
          v-if="editModel != 0"
          :loading="loading[1]"
          type="primary"
          class="button_right"
          @click="handleSubmit(2)"
        >
          提交
        </a-button>
        <a-button
          type="primary"
          @click="handleActiveClose"
        >
          关闭
        </a-button>
      </div>
    </a-form-model>
  </base-breadcrumb>
</template>

<script>
  import { create, update, detail, delayDetail } from '@/api/office/supervise' // api
  import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
  import TreeSelectOrganization from '@/components/TreeSelectOrganization'
  import Selector from '@/components/Select/Selector'
  import { getEmployeesList } from '@/api/commons.js'
  import { getLabels } from '@/api/office/supervise.js'
  import { getEmployees } from '@/api/businessAffairs/revenueAndCost'
  import moment from 'moment';

  export default {
    extends: new BaseEditPage(),
    props: {
      // 是否作为审批详情
      isAudit: {
        type: Boolean,
        default: false
      },
      // 是否作为意见征询
      isConsultation: {
        type: Boolean,
        default: false
      }
    },
    data() {
      return {
        loading: false, // 加载控件
        editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
        form: {
          feedbackVO: {
            feedbackFile: []
          },
          launchUnitId:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
          creatorId:JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
          launchDeptId:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId,
        }, // 表单
        rules: {
          lanuchUnitId: [{ required: true, whitespace: true, message: '督办发起单位未获取', trigger: 'change' }],
          launchDeptId: [{ required: true, message: '督办发起部门未获取', trigger: 'change' }],
          creatorId: [{ required: true, message: '经办人未获取', trigger: 'change' }],
          deptPrincipalId: [{ required: true, message: '请选择督办部门负责人', trigger: 'change' }],
          matterTypeId: [{ required: true, message: '请选择督办事项分类', trigger: 'change' }],
          planCompleteTime: [{ required: true, message: '请选择计划完成时间 ', trigger: 'change' }],
          matter: [{ required: true, message: '请输入督办事项 ', trigger: 'change' }],
          contentAbstract: [{ required: true, message: '请输入内容摘要及办理要求', trigger: 'change' }],
          princi: [{ required: true, message: '请选择承办领导、部门负责人', trigger: 'blur' }],
        }, // 校验规则
        init: false, // 初始化控件
        formCode: '', // 形式选中项code
        deptPrincipalData:[], //督办部门负责人数据
        matterTypeArr:[], //督办事项分类数据
        principalJobsData:[], //督办部门负责人
        businessType: this.$route.params.businessType,
        businessId: this.$route.params.businessId,
      }
    },
    watch: {
    },
    computed: {
      resultList() {
        return [
          {
            keyName: 'undertakeResult',
            viewName: 'feedbackVO',
            type: 'BaseTextarea',
            label: '承办结果',
            disabled:true,
            customRender(i){
              if(i){
                return i.undertakeResult
              }
            },
            span:24
          },
          {
            keyName: 'feedbackTime',
            viewName: 'feedbackVO',
            type: 'a-date-picker',
            placeholder: '请选择日期',
            label: '实际反馈时间',
            disabled:true,
            attrs: {
              valueFormat: 'YYYY-MM-DD',
            },
            customRender(i){
              if(i){
                return i.feedbackTime
              }
            },
          },
          {
            slot: true,
            keyName: 'feedbackList',
            label: '附件',
            span: 24,
          },
        ]
      },
      delayApplyList() {
        return [
          {
            keyName: 'delayReason',
            viewName: 'delayApplyVO',
            type: 'BaseTextarea',
            label: '延期申请原因',
            disabled:true,
            customRender(i){
              if(i){
                return i.delayReason
              }
            },
            span:24
          },
          {
            keyName: 'delayCompleteTime',
            viewName: 'delayApplyVO',
            type: 'a-date-picker',
            placeholder: '请选择日期',
            label: '延期后完成时间',
            disabled:true,
            attrs: {
              valueFormat: 'YYYY-MM-DD',
            },
            customRender(i){
              if(i){
                return i.delayCompleteTime
              }
            },
          },
          {
            slot: true,
            keyName: 'delayApplyfileList',
            label: '附件',
            span: 24,
          },
        ]
      },
      formList() {
        return [
          {
            keyName: 'launchUnitId',
            viewName: 'launchUnitName',
            type: 'a-select',
            disabled:true,
            label: '督办发起单位',
            data: [
              {
                value:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id,
                label:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.name
              }
            ]
          },
          {
            keyName: 'launchDeptId',
            viewName: 'launchDeptName',
            type: 'a-select',
            disabled:true,
            label: '督办发起部门',
            data: [
              {
                value:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId,
                label:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptName
              }
            ]
          },
          {
            keyName: 'creatorId',
            viewName: 'creatorName',
            label: '经办人',
            type: 'a-select',
            disabled:true,
            data: [
              {
                value:JSON.parse(sessionStorage.getItem('ycloud-user_info')).id,
                label:JSON.parse(sessionStorage.getItem('ycloud-user_info')).name
              }
            ]
          },
          {
            keyName: 'deptPrincipalId',
            viewName: 'deptPrincipalName',
            label: '督办部门负责人',
            type: 'a-select',
            data: this.deptPrincipalData,
            replaceFields: {
              value: 'userId', // 默认为value
              label: 'name' // 默认为label
            },
          },
          {
            keyName: 'matterTypeId',
            viewName: 'matterType',
            label: '督办事项分类',
            type: 'a-select',
            data: this.matterTypeArr,
            replaceFields: {
              value: 'id', // 默认为value
              label: 'name' // 默认为label
            },
            customRender(i){
              if(i){
                return i.name
              }
            }
          },
          {
            keyName: 'planCompleteTime',
            type: 'a-date-picker',
            placeholder: '请选择日期',
            label: '计划完成时间',
            attrs: {
              valueFormat: 'YYYY-MM-DD',
              disabledDate: (current) => {
                return current && current < moment().endOf('day')
              }
            },
          },
          {
            keyName: 'matter',
            type: 'BaseTextarea',
            label: '督办事项',
            span:24
          },
          {
            keyName: 'contentAbstract',
            type: 'BaseTextarea',
            label: '内容摘要及办理要求',
            span:24
          },
          {
            keyName: 'princi',
            viewName: 'principalJobs',
            label: '承办部门负责人',
            type: 'BaseTextarea',
            // type: 'a-select',
            // typeGroup: 'a-select-opt-group',
            // data: this.principalJobsData,
            // optGroup:true,
            // attrs:{
            //   labelInValue:true,
            //   optionFilterProp:'children',
            //   filterOption(input, option) {
            //     let children = option.componentOptions.children[0].children
            //     let text = children ? children[1].text : option.componentOptions.children[0].text
            //     return text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            //   },
            //   showSearch:true
            // },
            // replaceFields: {
            //   label: 'name', // 父级label
            //   childValue: 'userId', // 子级value
            //   childLabel: 'name', // 子级label
            //   childOpt: 'postParentList', //其他
            // },
            // customRender(i,j){
            //   console.log(11, i, j)
            //   if(i && j && i.userId && j[0].id){
            //     return i.userId+'/'+j[0].id
            //   // }else if(i && !j){
            //   }else if(i){
            //     return i
            //   }
            // },
            // customRenderLabel(i,j){
            //   console.log(22, i, j)
            //   if(i && j && i.userId && j[0].id){
            //     return i.name+': '+j[0].name
            //   }
            // },
            span:24,
          },
        ]
      },
    },
    methods: {
      /**
       * 获取承办部门负责人
       */
      handleEmployees(){
        const id=JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.id
        getEmployees({pageNumber:1,pageSize:10,queryPostRelation:true,rootOrgId:id}).then((res)=>{
          this.principalJobsData=res.data.list
        }).catch(()=>{
        })
      },
      /**
       * 校验表单
       */
      handleSubmit(val) {
        if(val =='2'){
          // 提交表单
          // 校验表单
          this.$refs.ruleForm.validate((e) => {
            if (e) {
              this.handleSubmitApi(val)
            }
          })
        }else{
          //保存表单
          this.handleSubmitApi(val)
        }
      },
      /**
       * 提交表单
       */
      handleSubmitApi(val){
        let that = this
        let api = [update, create][that.editModel - 1] // 根据操作切换url地址
        that.loading = true
        let formData = that.$clone(that.form)
        let princi=formData.princi ? formData.princi.key.split('/') : []
        let form={
          ...formData,
          principal: princi[0] || '',
          principalJobsId: princi[1] || '',
          principalJobs: formData.princi ? formData.princi.label : '',
          overseeStatus: val=='2' ? 'NO_FEEDBACK' : 'DRAFT', //结果已提交未反馈：NO_FEEDBACK； 待提交：DRAFT
        }
        api(form)
          .then(() => {
            that.loading = false
            if(val=='2'){
              that.$message.success('提交成功！')
            }else {
              that.$message.success('保存成功！')
            }
            that.$multiTab.close()
          })
          .catch(() => {
            that.loading = false
          })

      }
    },
    mounted(){
      if(this.businessType == 901){
        this.$route.meta.title = ['督办事项查看', '督办事项编辑', '督办事项新增'][this.editModel]
      }else if(this.businessType == 902){
        this.$route.meta.title = ['承办事项查看', '承办事项编辑', '承办事项新增'][this.editModel]
      }
      /**
       * 不为添加时请求详情
       * */
      if (this.editModel != 2) {
        this.loading = true
        let api = [detail, delayDetail][this.businessType - 901] // 根据操作切换url地址
        api({id:this.businessId})
          .then((res) => {
            this.loading = false
            this.form = res.data
            this.form.matterTypeId = res.data.matterType.id
            this.form.princi={
              key:res.data.principalJobsId,
              label:res.data.principalJobs
            }
            this.$nextTick(() => {
              this.init = true
            })
          })
          .catch(() => {
            this.loading = false
          })
      } else {
        this.$nextTick(() => {
          this.init = true
        })
      };
      /**
       * 督办部门负责人
       * */
      getEmployeesList({orgId:JSON.parse(sessionStorage.getItem('ycloud-user_info')).currentPost.deptId}).then((res) => {
        this.deptPrincipalData=res.data
      }).catch(() => {
      });

      /**
       * 督办事项分类
       **/
      getLabels({query:{type:'6'}}).then((res)=>{
        this.matterTypeArr=res.data
      }).catch(()=>{
      });

      this.handleEmployees()
    }
  }
</script>

<style lang="less" scoped>
    /deep/ .ant-form-item {
        .ant-form-item-label {
            height: 28px;
            width: 200px;
            line-height: 22px;
            padding: 6px 4px 0 0;
            text-align: right;
            white-space: pre-wrap;
            overflow: visible;
        }
        .ant-form-item-control-wrapper {
            width: calc(100% - 200px);
        }
    }
    .file_prompt {
        color: #999;
    }
</style>